﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OAuth2.Provider.IService;
using OAuth2.Repository;
using OAuth2.Framework;
using OAuth2.Framework.Model;

namespace OAuth2.Provider.Service
{
    public class TokenService:ITokenService
    {
        readonly IClientRepository ClientRepo;
        readonly ITokenRepository TokenRepo;

        public TokenService(IClientRepository clientRepo, ITokenRepository tokenRepo) {
            ClientRepo = clientRepo;
            TokenRepo = tokenRepo;
        }

        #region ITokenService 成员

        public IToken IssueAccessToken(AuthorizationGrantModel grant)
        {
            AccessTokenModel token = new AccessTokenModel() { 
                 ExpiresIn=120,
                  Token=Guid.NewGuid().ToString(),
                   Grant=(AuthorizationGrantModel)grant
            };
            token.Scope = new string[] { "view","edit" };
            TokenRepo.AddAccessToken(token);
            return token;
        }

        public IToken IssueAccessTokenForResourceOwner(ITokenContext context)
        {
            AccessTokenModel token = new AccessTokenModel { 
                ExpiresIn=120,
                 Token=Guid.NewGuid().ToString(),
                 RefreshToken=Guid.NewGuid().ToString(),
                 Scope=new string[]{"create","delete","view"}
            };
            TokenRepo.AddAccessToken(token);
            return token;
        }

        public IToken IssueAccessToken(RefreshTokenModel refreshToken)
        {
            AccessTokenModel token = new AccessTokenModel
            {
                ExpiresIn = 120,
                Token = Guid.NewGuid().ToString(),
                RefreshToken = refreshToken.Token,
                Scope = refreshToken.Scope,
                TokenType = "bearer"
            };
            TokenRepo.AddAccessToken(token);
            return token;
        }

        public IToken IssueAccessToken(IClient client)
        {
            AccessTokenModel token = new AccessTokenModel { 
                ExpiresIn=120,
                Token=Guid.NewGuid().ToString(),
                Scope=new string[]{"create-member"},
                Client=client
            };
            TokenRepo.AddAccessToken(token);
            return token;
        }

        public AccessTokenModel FindToken(string token)
        {
            return TokenRepo.FindToken(token);
        }

        public RefreshTokenModel FindRefreshToken(string refreshToken)
        {
            return TokenRepo.FindRefreshToken(refreshToken);
        }

        #endregion
    }
}
